<?php

namespace Home\Controller;
use Home\Org\Util\Sqlserver;
use Home\Model\DpQuestionCategoryModel;
use Home\Model\DpQuestionCategoryMappingUserModel;

use Org\Util\UploadFile;

use Home\Org\Util\QQOpenConfig;
use \Home\Org\Util\QQOpenHelper;

use Home\Org\Util\BizEmailConfig;

use Home\Org\Util\TelephonesysDatabase;

/**
 * 工单
 * @author dem
 *
 */
class WkorderController extends HomeController {
    
    
    /**
     * 新增工单
     */
    function create(){
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $this -> assign("plugin", $plugin);
        $this->display();
    }
    
    function upload() {
        $this -> _upload();
    }
    
    function docreate(){
        if(IS_POST){
            $res = 0;
            $data = json_decode($_POST['data'],1);
            $date = date('Y-m-d H:i:s');
            $remarks = $_POST['remarks'];
            $model = M('Wkorder');
            $user  = session('user_name');
            if($data){
                $wk_no =$user.date('YmdHis');
                foreach ($data as $vo){
                    $vo['ctime'] = $date;
                    $vo['wk_no'] = $wk_no;
                    $vo['remarks'] = $remarks;
                    $vo['createuser'] =$user;
                    $senduser = strpos($vo['senduser'],'-')!=false?explode('-', $vo['senduser'])[1]:$vo['senduser'];
                    $vo['senduser'] = $senduser;
                    $res=$model->add($vo);
                }
                    if($res){
                        //发送邮件
                        $tomail = $data[0]['senduser'];
                        $tomail = explode('-', $tomail);
                        $tomail = count($tomail)>1?$tomail[1]:$tomail[0];
                        $connent= $this->getorderHtml($wk_no);
                        $sendres = $this->sendEmail($tomail.'@g-town.com.cn', "收到新工单-".$data[0]['orderid'], $connent);
                        $connent = " 订单号:{$data[0]['orderid']}\n 物料名称:{$data[0]['goodsname']}\n 客户名称:{$data[0]['customer']} \n 快递单号:{$data[0]['expno']} \n 发起人:$user \n 请及时登陆OA系统处理";
                        //weixinsendmsg("[收到新工单-".$data[0]['orderid'].']', $connent, $tomail);
                    }
                
            }
           echo $res;
        }
        
    }
    
    function queryOrder(){
        $orderid = I('orderid');
        $sql = "SELECT U_ItemName goodsname,U_ItemCode goodsspu,u_orderid orderid,u_cstname customer ,u_expcom expcom,u_expno expno ,u_address address ,u_phone tel ,u_pmanager senduser  from [@TI_Z0081] where U_OrderId='{$orderid}'";
        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver();
        $data = $sqlser->query($sql);
        echo json_encode(array('total'=>count($data),'data'=>$data));
        exit;
    }
    
    
    
    /**
     * 查询工单
     */
    function query(){
        $key = I('keyword');
        $type = I('type');
        $map=[];
          if(isset($_POST['type'])||$type){
                if($type>=0)
            $map['status'] = array('eq', $type);
        }
        if($key){
            $map['orderid'] = array('like',  '%' . trim($key) . '%');
        }
        $model = M("Wkorder");
        $res= $this -> _listBywkorder($model, $map, 'id desc');
        $this->display();
    }
    
    /**
     * 我的工单
     */
    function myorder(){
        session('myorderUrl','http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        $key = I('keyword');
        $type = I('type');
        $map=[];
        $user  = session('user_name');
        $map['concat(createuser,senduser)'] = array('like',  '%' . trim($user) . '%');
        if(isset($_POST['type'])||$type){
            if($type>=0)
            $map['status'] = array('eq', $type);
        }
        if($key){
            $map['orderid'] = array('like',  '%' . trim($key) . '%');
        }
        $model = M("Wkorder");
        $res= $this -> _listBywkorder($model, $map, 'status,ctime desc');
        $this->display();
    }
    
    
    
    function info(){
        $code = I('code');
        $model = M("Wkorder");
        $data =  $model->where("wk_no='{$code}'")->select();
        $this->assign('data',json_encode($data,JSON_UNESCAPED_UNICODE));
        $this->assign('orderid',$data[0]['orderid']);
        $this->assign('remarks',$data[0]['remarks']);
        $this->assign('isaccess',false);
        $issaveend = $data[0]['createuser']==session('user_name')?true:false;
        $this->assign('issaveend',$issaveend);
        $model = M("Wkorderinfo");
        $orderinfo = $model->where("wk_no='{$code}'")->select();
        $this->assign("wkinfo",$orderinfo);
        $this->display('access');
        
    }
    
    
    function access(){
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $isaccess = true;
        $this -> assign("plugin", $plugin);
        $code = I('code');
        $model = M("Wkorder");
        $data =  $model->where("wk_no='{$code}'")->select();
        $this->assign('wk',$data[0]);
        $this->assign('data',json_encode($data,JSON_UNESCAPED_UNICODE));
        $model = M("Wkorderinfo");
        $issaveend = $data[0]['createuser']==session('user_name')?true:false;
        if( $data[0]['status']==2) $isaccess=false;
        $this->assign('issaveend',$issaveend);
        $orderinfo = $model->where("wk_no='{$code}'")->select();
        $this->assign('orderid',$data[0]['orderid']);
        $this->assign('remarks',$data[0]['remarks']);
        $this->assign("wkinfo",$orderinfo);
        $this->assign('isaccess',$isaccess);
        $this->display();
    
    }
    
    
    function saveend(){
        if(IS_POST){
            $wk_no = I('wk_no');
            $user  = session('user_name');
            M('Wkorder')->where("wk_no='{$wk_no}'")->save(array('status'=>2,'utime'=>date('Y-m-d H:i:s'),'lastuser'=>$user));
            $vo = array();
            $vo['connent'] = "完结工单";
            $vo['user'] = $user;
            $vo['wk_no'] = $wk_no;
            $vo['ctime'] = date('Y-m-d H:i:s');
            $res=M('Wkorderinfo')->add($vo);
            $this->ajaxReturn(array('res'=>$res,'url'=>session('myorderUrl')));
        }
    }
    /**
     * 回复工单
     */
    function saveaccess(){
        if(IS_POST){
            $res = 0;
            $wk_no = I('wk_no');
            $remarks = $_POST['remarks'];
            $model = M('Wkorderinfo');
            $user  = session('user_name');
            $wkinfo = M('Wkorder')->where("wk_no='$wk_no'")->find();
            $isPMAccess = $user==$wkinfo['createuser']?false:true; //是否为产品经理回复  是则状态改为已处理 否在状态为待处理
            if($wk_no&&$remarks){
                    $vo = array();
                    $vo['connent'] = $remarks;
                    $vo['user'] = $user;
                    $vo['wk_no'] = $wk_no;
                    $vo['ctime'] = date('Y-m-d H:i:s');
                    $res=$model->add($vo);
                    if($res){
                        M('Wkorder')->where("wk_no='{$wk_no}'")->save(array('status'=>$isPMAccess?1:0));
                        $toMail = $wkinfo['senduser'];
                        if($isPMAccess){
                            //产品回复
                            $toMail= $wkinfo['createuser'];
                        }
                        M('Wkorder')->where("wk_no='$wk_no'")->save(array('utime'=>date('Y-m-d H:i:s'),'lastuser'=>$user));
                        $url ='HTTP://'.$_SERVER["HTTP_HOST"]."/index.php?m=&c=wkorder&a=access&code=$wk_no";
                        $connent = "订单号:{$wkinfo['orderid']},<br/>回复内容:<br/>{$remarks} <br/>回复时间:{$vo['ctime']}<br/> <a href='$url'>点击这里处理工单</a>";
                        $sendres = $this->sendEmail($toMail.'@g-town.com.cn', "工单-{$wkinfo['orderid']}有新回复", $connent);
                        //weixinsendmsg("工单-{$wkinfo['orderid']}有新回复", "回复人:$user \n请及时登陆OA系统处理", $toMail);
                    }
                
            }
            $this->ajaxReturn(array('res'=>$res,'url'=>session('myorderUrl')));
        }
    
    }
    

    
    /**
     * 根据工单号生成邮件内容
     * @param unknown $wk_no
     * @return mixed
     */
    private function getorderHtml($wk_no){
        $keyArray = array(
            '%remarks%',
            '%orderid%',
            '%goodsspu%',
            '%goodsname%',
            '%customer%',
            '%tel%',
            '%address%',
            '%expmsg%',        
        );
        $data = M('Wkorder')->where("wk_no='$wk_no'")->select();
        $goodsspu = '';
        $goodsname = '';
        $expmsg = '';
        foreach ($data as $vo) {
            $expmsg .= $vo['expcom'].":".$vo['expno'] . ' ';
            $goodsspu = $vo['goodsspu'] . ' ';
            $goodsname = $vo['goodsname'] . ' ';
        }
        
        $replaces = array(
            $data[0]['remarks'],
            $data[0]['orderid'],
            $goodsspu,
            $goodsname,
            $data[0]['customer'],
            $data[0]['tel'],
            $data[0]['address'],
           $expmsg
        );
        $url ='HTTP://'.$_SERVER["HTTP_HOST"]."/index.php?m=&c=wkorder&a=access&code=$wk_no";
        $str = <<<html
工单内容:<br/>
					   &nbsp;&nbsp;%remarks%<br/><br/>					
					订单%orderid%信息:<br/>
					<p>物料号:%goodsspu%</p>
					<p>物料名称:%goodsname%</p>
					<p>客户姓名:%customer%</p>
                    <a href="$url">点击这里处理工单</a>
html;
        return str_replace($keyArray, $replaces, $str);
    }

    /** MARK 新工单 Begin **/

    /**
     * 新增工单
     */
    function createdp20171120(){
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $this -> assign("plugin", $plugin);
        $this->display();
    }

    function getUserlist()
    {
        $userModel = M('User');
        $user = session('emp_no');
        $list = $userModel->order('id asc')->select();
        echo json_encode($list, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * 获取问题种类清单
     */
    function getQuestionCategory()
    {
        $data = DpQuestionCategoryModel::getInstance()->getAllCategoryTree();
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * 创建DP工单
     */
    function docreatedp20171120(){
        if(IS_POST){
            $res = 0;
            $categoryID = $_POST['categoryID'];
            $date = date('Y-m-d H:i:s');
            $qSubject = $_POST['qSubject'];
            $remarks = $_POST['remarks'];
            $qRequestMan = $_POST['qRequestMan'];
            $model = M('dpWkorder');
            $user  = session('user_name');
            if($categoryID){
                // 类型层级清单 - 入库
                $categoryList = DpQuestionCategoryModel::getInstance()->getParentCategoryByID($categoryID);
                $vo['category_list'] = $categoryList;

                // 权重清单,当前权重 - 入库
                $qWeightArray = DpQuestionCategoryMappingUserModel::getQWeightByCategoryIDList($categoryList);
                $vo['q_weight_list'] = $qWeightArray['qWeightList'];
                $vo['c_q_weight'] = $qWeightArray['cQWeight'];

                $wk_no =$user.date('YmdHis');
                $vo['ctime'] = $date;
                $vo['wk_no'] = $wk_no;
                $vo['q_subject'] = $qSubject;
                $vo['request_man'] = $qRequestMan;
                $vo['remarks'] = $remarks;
                $vo['createuser'] =$user;

                // 通知用户清单 - 需要入库
                $toUserList = DpQuestionCategoryMappingUserModel::getUserListByCategoryIDListANDQWeight($categoryList,$qWeightArray['cQWeight']);
                $senduser = $toUserList;
                $vo['senduser'] = $senduser;
                $res=$model->add($vo);
                if($res){
                    // 保存成功后发送邮件
                    // 发起人 $user
                        $this->sendEmail($user.'@g-town.com.cn', "您发起：".$qSubject, $remarks);
                    // 请求人
                    if($qRequestMan) {
                        $this->sendEmail($qRequestMan . '@g-town.com.cn', "您请求：" . $qSubject, $remarks);
                    }
                    // 接收人
                    $senduserArray = explode(',',$senduser);
                    foreach ($senduserArray as $key => $item){
                        $this->sendEmail($item . '@g-town.com.cn', "您有新请求：" . $qSubject, $remarks);
                    }
                }

            }
            echo $res;
        }

    }

    /**
     * 我的DP工单
     */
    function myorderdp20171120(){
        session('myorderUrl','http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        $type = I('type');
        $map=[];
        $user  = session('user_name');
        $map['concat(createuser,senduser)'] = array('like',  '%' . trim($user) . '%');
        if(isset($_POST['type'])||$type){
            if($type>=0)
                $map['status'] = array('eq', $type);
        }
        $model = M("dpWkorder");
        $res= $this -> _listBywkorder($model, $map, 'status,ctime desc');
        $this->display();
    }

    /**
     * 查询DP工单
     */
    function querydp20171120(){
        $type = I('type');
        $map=[];
        if(isset($_POST['type'])||$type){
            if($type>=0)
                $map['status'] = array('eq', $type);
        }
        $model = M("dpWkorder");
        $res= $this -> _listBywkorder($model, $map, 'id desc');
        $this->display();
    }

    /**
     * 回复工单
     */
    function accessdp20171120(){
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $isaccess = true;
        $this -> assign("plugin", $plugin);
        $code = I('code');
        $model = M("dpWkorder");
        $data =  $model->where("wk_no='{$code}'")->select();
        $this->assign('wk',$data[0]);
        $this->assign('data',json_encode($data,JSON_UNESCAPED_UNICODE));
        $model = M("dpWkorderinfo");

        // 只有创建者可以完结工单
        $issaveend = $data[0]['createuser']==session('user_name')?true:false;
        $this->assign('issaveend',$issaveend);

        if(strpos($data[0]['senduser'],session('user_name')) === false){
            $canOp = false;
        }else{
            $canOp = true;
        }
        $this->assign('canOp',$canOp);

        $qWeightArray = explode(',',$data[0]['q_weight_list']);
        $cQWeight = $data[0]['c_q_weight'];

        if($qWeightArray[0] == $cQWeight){
            // 不能再降级了
            $canGoDown = false;
        }else{
            $canGoDown = true;
        }
        $this->assign('canGoDown',$canGoDown);

        if($qWeightArray[count($qWeightArray)-1]==$cQWeight){
            // 不能再升级了
            $canGoUp = false;
        }else{
            $canGoUp = true;
        }
        $this->assign('canGoUp',$canGoUp);

        if( $data[0]['status']==2) $isaccess=false;
        $orderinfo = $model->where("wk_no='{$code}'")->select();

        $cnCategoryChain = DpQuestionCategoryModel::getInstance()->getCNCategoryChainbyIDList($data[0]['category_list']);

        $this->assign('orderid',$data[0]['orderid']);
        $this->assign('qSubject',$data[0]['q_subject']);
        $this->assign('requestMan',$data[0]['request_man']);
        $this->assign('cnCategoryChain',$cnCategoryChain);
        $this->assign('remarks',$data[0]['remarks']);
        $this->assign("wkinfo",$orderinfo);
        $this->assign('isaccess',$isaccess);
        $this->assign('score',$data[0]['star_rating']);
        $this->display();

    }

    /**
     * 回复dp工单
     */
    function saveaccessdp20171120(){
        if(IS_POST){
            $res = 0;
            $wk_no = I('wk_no');
            $remarks = $_POST['remarks'];
            $model = M('dpWkorderinfo');
            $user  = session('user_name');
            $wkinfo = M('dpWkorder')->where("wk_no='$wk_no'")->find();
            $isPMAccess = $user==$wkinfo['createuser']?false:true; //是否为创建者回复  是则状态改为已处理 否在状态为待处理
            if($wk_no&&$remarks){
                $vo = array();
                $vo['connent'] = $remarks;
                $vo['user'] = $user;
                $vo['wk_no'] = $wk_no;
                $vo['ctime'] = date('Y-m-d H:i:s');
                $res=$model->add($vo);
                if($res){
                    M('dpWkorder')->where("wk_no='{$wk_no}'")->save(array('status'=>$isPMAccess?1:0));
                    /*$toMail = $wkinfo['senduser'];
                    if($isPMAccess){
                        $toMail= $wkinfo['createuser'];
                    }*/
                    M('dpWkorder')->where("wk_no='$wk_no'")->save(array('utime'=>date('Y-m-d H:i:s'),'lastuser'=>$user));
                    // 保存后发出邮件
                    // 发起人
                    $this->sendEmail($wkinfo['createuser'].'@g-town.com.cn', "您发起：".$wkinfo['q_subject']." 有回复", $remarks);
                    // 请求人
                    if($wkinfo['request_man']) {
                        $this->sendEmail($wkinfo['request_man'] . '@g-town.com.cn', "您请求：" .$wkinfo['q_subject']." 有回复", $remarks);
                    }
                    // 接收人
                    $senduserArray = explode(',',$wkinfo['senduser']);
                    foreach ($senduserArray as $key => $item){
                        $this->sendEmail($item . '@g-town.com.cn', "请求：" . $wkinfo['q_subject']." 有回复", $remarks);
                    }
                }

            }
            $this->ajaxReturn(array('res'=>$res,'url'=>session('myorderUrl')));
        }

    }

    /**
     * 完结工单
     */
    function saveenddp20171120(){
        if(IS_POST){
            $wk_no = I('wk_no');
            $starRating = I('starRating');
            $user  = session('user_name');
            M('dpWkorder')->where("wk_no='{$wk_no}'")->save(array('status'=>2,'utime'=>date('Y-m-d H:i:s'),'lastuser'=>$user,'star_rating'=>$starRating));
            $vo = array();
            $vo['connent'] = "完结工单，并评分：".$starRating;
            $remarks = $vo['connent'];
            $vo['user'] = $user;
            $vo['wk_no'] = $wk_no;
            $vo['ctime'] = date('Y-m-d H:i:s');
            $res=M('dpWkorderinfo')->add($vo);

            $wkinfo = M('dpWkorder')->where("wk_no='{$wk_no}'")->find();
            if($wkinfo) {
                // 保存后发出邮件
                // 发起人
                $this->sendEmail($wkinfo['createuser'] . '@g-town.com.cn', "您发起：" . $wkinfo['q_subject'] . " 完结", $remarks);
                // 请求人
                if ($wkinfo['request_man']) {
                    $this->sendEmail($wkinfo['request_man'] . '@g-town.com.cn', "您请求：" . $wkinfo['q_subject'] . " 完结", $remarks);
                }
                // 接收人
                $senduserArray = explode(',', $wkinfo['senduser']);
                foreach ($senduserArray as $key => $item) {
                    $this->sendEmail($item . '@g-town.com.cn', "请求：" . $wkinfo['q_subject'] . " 完结", $remarks);
                }
            }

            $this->ajaxReturn(array('res'=>$res,'url'=>session('myorderUrl')));
        }
    }

    /**
     * 查询工单通往页面
     */
    function infodp20171120(){
        $code = I('code');
        $model = M("dpWkorder");
        $data =  $model->where("wk_no='{$code}'")->select();
        $this->assign('data',json_encode($data,JSON_UNESCAPED_UNICODE));
        $this->assign('orderid',$data[0]['orderid']);
        $this->assign('qSubject',$data[0]['q_subject']);
        $this->assign('remarks',$data[0]['remarks']);
        $this->assign('isaccess',false);
        $issaveend = $data[0]['createuser']==session('user_name')?true:false;
        $this->assign('issaveend',$issaveend);
        $model = M("dpWkorderinfo");
        $orderinfo = $model->where("wk_no='{$code}'")->select();

        $cnCategoryChain = DpQuestionCategoryModel::getInstance()->getCNCategoryChainbyIDList($data[0]['category_list']);

        $this->assign('cnCategoryChain',$cnCategoryChain);
        $this->assign("wkinfo",$orderinfo);
        $this->display('accessdp20171120');

    }

    function dpconfiguration20171120(){
        $this->display();
    }

    function exportdporder20171120(){
        $this->display();
    }

    function doexportdporder20171120(){

        $userID = $_REQUEST['qRequestMan'];
        $startDate = $_REQUEST['startDate'];
        $endDate = $_REQUEST['endDate'];
        //echo $userID.'/'.$startDate.'/'.$endDate;

        $dpWkorderModel = M('dpWkorder');
        // 检测 CTIME 字段
        $data = $dpWkorderModel->where(" ctime BETWEEN '".$startDate."' AND '".$endDate."' AND senduser like '%".$userID."%' ")->select();
        //状态 0 等待回复 1 已处理  2已完结
        $statusArray = array('等待回复','已处理','已完结');

        //Export to Excel:
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, 'ID');
        $currentSheet->setCellValue('B'.$m, '工单号');
        $currentSheet->setCellValue('C'.$m, '工单主题');
        $currentSheet->setCellValue('D'.$m, '工单创建人');
        $currentSheet->setCellValue('E'.$m, '需求请求人');
        $currentSheet->setCellValue('F'.$m, '需求响应人');
        $currentSheet->setCellValue('G'.$m, '工单创建时间');
        $currentSheet->setCellValue('H'.$m, '工单状态');
        $currentSheet->setCellValue('I'.$m, '工单更新时间');
        $currentSheet->setCellValue('J'.$m, '工单最后操作人');
        $currentSheet->setCellValue('K'.$m, '评分（1-5）');

        $cellIndex = 1;
        foreach ($data as $key => $value) {
            $cellIndex++;
            $currentSheet->setCellValueExplicit('A' . $cellIndex, $value['id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B' . $cellIndex, $value['wk_no'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('C' . $cellIndex, $value['q_subject'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('D' . $cellIndex, $value['createuser'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('E' . $cellIndex, $value['request_man'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('F' . $cellIndex, $value['senduser'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('G' . $cellIndex, $value['ctime'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('H' . $cellIndex, $statusArray[$value['status']], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('I' . $cellIndex, $value['utime'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('J' . $cellIndex, $value['lastuser'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('K' . $cellIndex, $value['star_rating'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    function listAllQuestionCategory(){
        $data = DpQuestionCategoryModel::getInstance()->getAllCategoryData();
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    function updateQuestionCategory(){
        $data = json_decode(I('data'), 1);
        DpQuestionCategoryModel::getInstance()->updateQuestionCategory($data);
    }

    function listAllQuestionCategoryMappingUser(){
        $data = DpQuestionCategoryMappingUserModel::getInstance()->getAllMappingData();
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    function updateQuestionCategoryMappingUser(){
        $data = json_decode(I('data'), 1);
        DpQuestionCategoryMappingUserModel::getInstance()->updateQuestionCategoryMappingUser($data);
    }

    /**
     * 向上级转发
     */
    function ordergoupdp20171120(){
        if(IS_POST){
            $wk_no = I('wk_no');
            $user  = session('user_name');

            // 1. 更新当前权重,修改接收人
            $toUserList = $this->updateDpOrderQWeight($wk_no,$user,"goup");

            // 2. 将操作记录插入Info表
            $result = $this->updateDpOrderInfo($wk_no,$user,"转发了工单,新接收人为:".$toUserList);

            $this->ajaxReturn(array('res'=>$result,'url'=>session('myorderUrl')));
        }
    }

    /**
     * 向下级转发
     */
    function ordergodowndp20171120(){
        if(IS_POST){
            $wk_no = I('wk_no');
            $user  = session('user_name');

            // 1. 更新当前权重,修改接收人
            $toUserList = $this->updateDpOrderQWeight($wk_no,$user,"godown");

            // 2. 将操作记录插入Info表
            $result = $this->updateDpOrderInfo($wk_no,$user,"转发了工单,新接收人为:".$toUserList);

            $this->ajaxReturn(array('res'=>$result,'url'=>session('myorderUrl')));
        }
    }

    function updateDpOrderInfo($wk_no,$user,$msg){

        $vo = array();
        $vo['connent'] = $user.': '.$msg;
        $vo['user'] = $user;
        $vo['wk_no'] = $wk_no;
        $vo['ctime'] = date('Y-m-d H:i:s');
        $result=M('dpWkorderinfo')->add($vo);
        return $result;

    }

    function updateDpOrderQWeight($wk_no,$user,$action){
        $dpWkorderModel = M('dpWkorder');
        $result = $dpWkorderModel->where(" wk_no = '{$wk_no}' ")->find();
        $categoryList = $result['category_list'];
        $cQWeight = $result['c_q_weight'];
        $qWeightArray = explode(',',$result['q_weight_list']);
        $tmpKey = 0;
        foreach ($qWeightArray as $key => $item){
            if($item == $cQWeight)
            {
                $tmpKey = $key;
                break;
            }
        }
        // 新权重
        switch ($action)
        {
            case 'goup':
                $newCQWeight = $qWeightArray[$tmpKey+1];
                break;
            case 'godown':
                $newCQWeight = $qWeightArray[$tmpKey-1];
                break;
            default:
                break;
        }

        // 升级后通知的用户
        $toUserList = DpQuestionCategoryMappingUserModel::getUserListByCategoryIDListANDQWeight($categoryList,$newCQWeight);
        $dpWkorderModel->where("wk_no='{$wk_no}'")->save(array('status'=>0,'utime'=>date('Y-m-d H:i:s'),'lastuser'=>$user,'c_q_weight'=>$newCQWeight,'senduser'=>$toUserList));
        return $toUserList;

    }

    /** MARK 新工单 End **/

    /** MARK GT IT 创建账号 Begin **/
    /**
     * @Description: 通过导入EXCEL创建账号
     */
    function uploadExcelToCreateAccounts(){
        $this->display();
    }

    function doUploadExcelToCreateAccounts()
    {
        $tag =time();
        $today = date("Y-m-d H:i:s");
        $time = $today;
        // excel 表头 与 mysql 表头对应关系
        $orderHeadArray = array(
            '中文名' =>'cn_name', //A
            '英文名' =>'en_name', //B
            '部门' =>'dept', //C
            '组' =>'group_name', //D
            '工号' =>'gt_emp_no', //E

            '职位' =>'title', //F
            '性别' =>'gender', //G
            '手机号' =>'mob_phone', //H
            '分机号' =>'tel_ext' //I

        );

        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config = array(
                'allowExts' => array('xlsx', 'xls'),
                'savePath' => './exceltojh/',
                'saveRule' => 'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {

                $info = $upload->getUploadFileInfo();
                $theType = $info[0]['type'];
                //echo $theType;die();
                if($theType != "application/vnd.ms-excel" && $theType != "application/octet-stream" && $theType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    //var_dump($theType);die();
                    $this->assign('errorInfo',"文件类型错误！");
                    $this->display('uploadExcelToCreateAccounts');
                    return;
                }

                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;

                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value) {
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value) {
                    if (empty($value)) {
                        unset($excelHead[$key]);
                    }
                }
                // Table表头与Excel列对应关系
                //var_dump($excelHead);
                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;
                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $inkey => $value) {
                        //Core
                        $targetData[$excelHead[$inkey]] = trim($value);
                    }
                    unset($targetData['']);

                    // 补全数据
                    $targetData['gmt_create'] = $time;
                    $targetData['gmt_modified'] = $time;
                    $targetData['upload_emp_no'] = session('emp_no');

                    //$targetData['pass_word'] = "12@Gtown21"; //$this->generatePassword();
                    $targetData['pass_word'] = $this->randAPassword();

                    $str = "'" . implode("','", $targetData) . "'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";

                }
                $sql = " insert into think_created_user_it  (" . implode(',', array_keys($targetData)) . ") values $mergeStr";
                //echo $sql;die();

                $createdUserITModel = M('createdUserIt');
                $result = $createdUserITModel->execute($sql);
                $return = 0;
                $errorStr = '导入不成功！';
                if ($result) {
                    $return = 1;
                    $errorStr = '导入成功！';
                }
                //echo json_encode(array('data' => $return, 'msg' => $errorStr), 1);

                $this->assign('errorInfo',$errorStr);
                $this->display('uploadExcelToCreateAccounts');

            }
        }
    }

    public function listUserFromExcel()
    {
        $this->display();
    }

    public function getListUserFromExcel()
    {
        $model =M('createdUserIt');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $where='1 = 1 ';
        $all =$model->where($where)->order("id desc")->select();
        $total = count($all);
        $res = $model->where($where)->order("id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }

    public function doCreateUser(){

        $respone = array('code'=>0,'msg'=>'成功');

        $id = I('id');
        $type = I('type');
        //var_dump($id.'='.$type);die();

        $date = date('Y-m-d H:i:s');
        $operator = session('emp_no');

        // 权限控制 Table: think_it_operator
        $itOperatorModel = M('itOperator');
        $checkPermmission = $itOperatorModel->where("emp_no = '{$operator}'")->find();

        if($checkPermmission['id']){

            // do the job
            switch ($type)
            {
                case 'all':
                    $respone = $this->createAllAccounts($id);
                    break;
                case 'domain':
                    $respone = $this->createDomainAccount($id);
                    break;
                case 'email':
                    $respone = $this->createEmailAccount($id);
                    break;
                case 'qq':
                    $respone = $this->createQQAccount($id);
                    break;
                default:
                    break;
            }

        }else{
            $respone = array('code' => 0, 'msg' => '没有权限执行此操作！');
        }

        echo json_encode($respone);
        exit;

    }

    public function generatePdf(){

        $id = I('id');
        $createdUserItModel = M('createdUserIt');
        $data = $createdUserItModel->where('id ='.$id)->find();

        Vendor('mpdf60.mpdf');
        $mpdf=new \mPDF('zh-cn','A4', 0, '宋体', 10, 10);
        /*$html="<table align='center' width='90%' height='90%' border='1' cellpadding='0' cellspacing='0'>
<tr><td colspan='6' align='center'>员工：".$data['cn_name']."</td></tr>
<tr>
<td>工号:</td>
<td>姓名:</td>
<td>域帐号:</td>
<td>邮箱:</td>
<td>企业QQ:</td>
<td>密码:</td>
</tr>
<tr>
<td>".$data['gt_emp_no']."</td>
<td>".$data['cn_name']."</td>
<td>".$data['en_name']."</td>
<td>".$data['en_name']."@g-town.com.cn</td>
<td>".$data['en_name']."@g-town.com.cn</td>
<td>".$data['pass_word']."</td>
</tr>
<tr><td colspan='6' align='right'>海牙湾IT部</td></tr>
</table>";*/

        $html="<h1>海牙湾IT部的一封信</h1>
<p class=\"yahei\">Dear \"".$data['cn_name']."\" （工号：".$data['gt_emp_no']."），</p>
<p class=\"yahei\">你好，欢迎加入海牙湾大家庭！</p>
<p class=\"yahei\">在这里，你可以将理想付诸实践；在这里，你可以感受到一群有真爱的小伙伴；</p>
<p class=\"yahei\">在这里，你可以亲手创造产品，并享受成功的荣耀！</p>
<p class=\"yahei\">让我们一起，全力为理想与责任而努力工作！</p>

<h2>我们已经为你开设以下账号：</h2>

<table align='center' width='90%' height='90%' border='1' cellpadding='0' cellspacing='0'>
	<tr><td align='center'>AD域</td><td align='center'>AD域账号</td></tr>
	<tr><td align='center'>G-town\</td><td align='center'>".$data['en_name']."</td></tr>
</table>

<br>

<table align='center' width='90%' height='90%' border='1' cellpadding='0' cellspacing='0'>
	<tr><td align='center'>企业QQ</td><td align='center'>企业邮箱</td></tr>
	<tr><td align='center'>".$data['en_name']."@g-town.com.cn</td><td align='center'>".$data['en_name']."@g-town.com.cn</td></tr>
</table>

<br/>

<table align='center' width='90%' height='90%' border='1' cellpadding='0' cellspacing='0'>
	<tr><td align='center'>域账号、企业邮箱、企业QQ初始密码</td></tr>
	<tr><td align='center'>".$data['pass_word']."</td></tr>
    <tr><td align='center'>★此密码为初始密码，首次登陆后需要修改密码。</td></tr>
</table>

<h2>其他有用信息：</h2>
<p>OA通过域账号登录、企业QQ也可以通过邮箱登录</p>
<p>网页版邮箱登录网址为：http://mail.g-town.com.cn</p>
<p>OA登录网址为：http://OA.g-town.com.cn:8008</p>
<p>桌面支持邮箱：helpdesk@g-town.com.cn　　分机：8024</p>
<div>";

        $mpdf->WriteHTML($html);
        $mpdf->Output();
        exit;

    }

    public function generatePasswordForSpecialUser(){
        $id = I('id');
        $createdUserItModel = M('createdUserIt');
        $saveData = array('pass_word'=>$this->generatePassword());
        $updateTable = $createdUserItModel->where("id={$id}")->save($saveData);
        $respone = array('code' => 1, 'msg' => '已更新密码');
        echo json_encode($respone);
        exit;
    }

    protected $passwordArray = array(
        '2Wf8BnA#','Y4vURk4#','ZRI8tR3s#','gt9cqcjJ#','6q5PdjhJ#',
        '#P3wd4GZs','#QtHDIb72','#Bg4OK372','#ci8yfsmz','wxgHkC#7',
        'K2GvXZ3#','7nyxBzN#','5#mCEYWh','bqT8yN#U','WBkSz4H#',
        'sAw#h9Kr','Pg#8ezXk','F#i322sM',
    );

    protected function randAPassword(){
        $randomNum = rand(0,17);
        return $this->passwordArray[$randomNum];
    }

    protected function generatePassword(){

        $length = 8;

        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k','m', 'n', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z','2', '3', '4', '5', '6', '7', '8', '9', '!',
            '@','#', '$', '%', '&', '*', '(', ')', '-', '_',
            '[', ']', '{', '}', '<', '>', '~',  '+', '=', ',', ';', ':', '?', '|');

        $keys = array_rand($chars,8);

        $password = '';
        for($i = 0; $i < $length; $i++)
        {
            $password .= $chars[$keys[$i]];
        }

        //echo $password;
        return $password;

    }

    protected function createAllAccounts($id){

        $respone = array('code' => 0, 'msg' => 'AllAccounts！');
        return $respone;

    }

    protected function createDomainAccount($id){

        $createdUserItModel = M('createdUserIt');
        $data = $createdUserItModel->where('id='.$id)->find();

        // 本地执行 PowerShell 命令
        //$result = shell_exec('powershell.exe ls');

        $_utf8 = "C:\workspace\aduseradd.py ".$data['en_name']." ".$data['dept']." \"".$data['pass_word']."\" ".$data['gt_emp_no']." \"".$data['cn_name']."\""; // 英文名 部门名 密码 工号 中文名
        $_gbk = mb_convert_encoding($_utf8,'gbk','utf-8');
        $result = shell_exec($_gbk);
        $utf8Result = mb_convert_encoding($result,'utf-8','gbk');

        if($utf8Result == "success")
        {
            $respone = array('code' => 1, 'msg' => '成功创建域账号！');
            $saveData = array('is_ok_domain'=>1,'error_msg_domain'=>$utf8Result);
        }else{
            $respone = array('code' => 0, 'msg' => '创建域账号失败！');
            $saveData = array('is_ok_domain'=>0,'error_msg_domain'=>$utf8Result);
        }
        $updateTable = $createdUserItModel->where("id={$id}")->save($saveData);
        return $respone;
    }

    protected function getExmailToken(){

        import("@.ORG.Util.BizEmailConfig");
        $apiUrl = BizEmailConfig::API_URL_HEAD.'gettoken';
        $query = array(
            'corpid'=>BizEmailConfig::CORPID,
            'corpsecret'=>BizEmailConfig::CORPSECRET
        );
        $tokenDataJson = http($apiUrl,$query,'GET');
        $tokenDataArray = json_decode($tokenDataJson,true);
        return $tokenDataArray['access_token'];

    }

    public function getExmailDeptList(){

        import("@.ORG.Util.BizEmailConfig");
        $apiUrl = BizEmailConfig::API_URL_HEAD.'department/list';
        $query = array(
            'access_token'=>$this->getExmailToken()
        );
        $deptListJson = http($apiUrl,$query,'GET');
        $deptListObject = json_decode($deptListJson,false,512 , JSON_BIGINT_AS_STRING);

        $pureDeptArray = array();
        if($deptListObject->errmsg == 'ok')
        {
            $pureDeptArray = $deptListObject->department;
        }

        $convertDeptArray = array();
        foreach ($pureDeptArray as $key => $item)
        {
            $newItem = array('id'=>$item->id,'name'=>$item->name);
            $convertDeptArray[] = $newItem;
        }

        return $convertDeptArray;

    }

    protected function getExmailDeptID($deptCnName){
        $pureDeptArray = $this->getExmailDeptList();
        foreach ($pureDeptArray as $key => $item){
            if($deptCnName == $item['name'])
            {
                return $item['id'];
            }
        }
    }

    protected function createEmailAccount($id){

        import("@.ORG.Util.BizEmailConfig");
        $apiUrl = BizEmailConfig::API_URL_HEAD.'user/create?access_token='.$this->getExmailToken();

        $createdUserItModel = M('createdUserIt');
        $data = $createdUserItModel->where('id='.$id)->find();
        $deptID = $this->getExmailDeptID($data['dept']);
        //var_dump($deptID);
        //$deptID = number_format($deptID,0,'','');
        //echo $deptID;die();

        if($data['gender']=='男')
        {
            $gender = 1;
        }else{
            $gender = 2;
        }

        //$jsonData = "{\"userid\":\"apiTestingA.shi@g-town.com.cn\",\"name\":\"apiTestingA.shi\",\"department\":[34353631791819764],\"password\":\"ap1@Testing\"}";
        $jsonData = "{\"userid\":\"".$data['en_name']."@g-town.com.cn\",\"name\":\"".$data['cn_name']."\",\"department\":[".$deptID."],\"position\":\"".$data['title']."\",\"mobile\":\"".$data['mob_phone']."\",\"extid\":\"".$data['tel_ext']."\",\"gender\":\"".$gender."\",\"password\":\"".$data['pass_word']."\"}";

        //echo $jsonData;die();
        //echo $apiUrl;die();

        $resultJson = http($apiUrl,$jsonData,'POST');
        $resultArray = json_decode($resultJson,true);

        if($resultArray['errmsg'] == 'ok')
        {
            // update table: think_created_user_it
            $saveData = array('is_ok_email'=>1,'error_msg_email'=>$resultArray['errmsg']);
            $updateTable = $createdUserItModel->where("id={$id}")->save($saveData);
            $respone = array('code' => 1, 'msg' => '成功创建企业邮箱');
        }else {
            // update table: think_created_user_it
            $saveData = array('is_ok_email'=>0,'error_msg_email'=>$resultArray['errmsg']);
            $updateTable = $createdUserItModel->where("id={$id}")->save($saveData);
            $respone = array('code' => 0, 'msg' => '创建企业邮箱失败');
        }
        return $respone;

    }

    protected function getQQTokenFromDat(){
        import("@.ORG.Util.QQOpenConfig");
        $file = QQOpenConfig::FILE_NAME;
        $current = file_get_contents($file);
        $dataArray = json_decode($current,true);
        //var_dump($dataArray);
        $qqCompanyToken = $dataArray['data']['company_token'];
        return $qqCompanyToken;
    }

    protected function getQQDeptList(){
        // https://openapi.b.qq.com/api/dept/list?company_id=e75859f88b3d0083d4524057ec99975a&company_token=47638a5302e659e9314382f24ec60c96&app_id=201129618&client_ip=101.81.11.142&oauth_version=2

        import("@.ORG.Util.QQOpenConfig");
        $apiUrl = QQOpenConfig::API_URL_HEAD.'dept/list';
        $query = array(
            'company_id' => QQOpenConfig::COMPANY_ID,
            'company_token' => $this->getQQTokenFromDat(),
            'app_id' => QQOpenConfig::APPID,
            'client_ip' => QQOpenConfig::CLIENT_IP,
            'oauth_version' => QQOpenConfig::OAUTH_VERSION
        );

        $deptListJson = http($apiUrl,$query);
        $deptListArray = json_decode($deptListJson,true);

        if($deptListArray['msg'] == '调用成功')
        {
            $pureDeptArray = $deptListArray['data']['items'];
        }
        return $pureDeptArray;

    }

    protected function getQQDeptID($deptCnName){
        $pureDeptArray = $this->getQQDeptList();
        foreach ($pureDeptArray as $key => $item){
            if($deptCnName == $item['dept_name'])
            {
                return $item['dept_id'];
            }
        }
    }

    protected function createQQAccount($id){
        // https://openapi.b.qq.com/api/dept/adduser?company_id=e75859f88b3d0083d4524057ec99975a&company_token=47638a5302e659e9314382f24ec60c96&app_id=201129618&client_ip=101.81.11.142&oauth_version=2&account=apiTesting&name=apiTesting&password=ap1@Testing&p_dept_id=1021662957

        import("@.ORG.Util.QQOpenConfig");
        $apiUrl = QQOpenConfig::API_URL_HEAD.'dept/adduser';

        $createdUserItModel = M('createdUserIt');
        $data = $createdUserItModel->where('id='.$id)->find();

        $account = $data['en_name'];
        $name = $data['cn_name'];
        $deptCnName = $data['dept'];
        $groupCnName = $data['group_name'];
        $finalDeptCnName = '';
        if(!empty($groupCnName))
        {
            $finalDeptCnName = $groupCnName;
        }else{
            $finalDeptCnName = $deptCnName;
        }
        $password = $data['pass_word'];

        if($data['gender']=='男')
        {
            $gender = 1;
        }else{
            $gender = 2;
        }

        $mobile = $data['mob_phone'];
        $title = $data['title'];

        $query = array(
            'company_id' => QQOpenConfig::COMPANY_ID,
            'company_token' => $this->getQQTokenFromDat(),
            'app_id' => QQOpenConfig::APPID,
            'client_ip' => QQOpenConfig::CLIENT_IP,
            'oauth_version' => QQOpenConfig::OAUTH_VERSION,
            'account' => $account,
            'name' => $name,
            'password' => $password,
            'p_dept_id' => $this->getQQDeptID($finalDeptCnName),
            'gender' => $gender,
            'mobile' => $mobile,
            'title' => $title,
        );

        //var_dump($query);

        $resultJson = http($apiUrl,$query,'POST');
        $resultArray = json_decode($resultJson,true);

        if($resultArray['msg'] == '调用成功')
        {
            // update table: think_created_user_it
            $saveData = array('is_ok_qq'=>1,'error_msg_qq'=>$resultArray['msg']);
            $updateTable = $createdUserItModel->where("id={$id}")->save($saveData);
            $respone = array('code' => 1, 'msg' => '成功创建企业QQ');
        }else {
            // update table: think_created_user_it
            $saveData = array('is_ok_qq'=>0,'error_msg_qq'=>$resultArray['msg']);
            $updateTable = $createdUserItModel->where("id={$id}")->save($saveData);
            $respone = array('code' => 0, 'msg' => '创建企业QQ失败');
        }
        return $respone;

    }

    /**
     * @Description: 跳转至 QQ 开放平台，完成授权，获得 code -> token
     */
    public function getQQCodeForQQToken(){

        import("@.ORG.Util.QQOpenConfig");
        if (QQOpenConfig::APPID == '' || QQOpenConfig::APPSECRET == '' || QQOpenConfig::COMPANY_CALLBACK_URL == '' || QQOpenConfig::USER_CALLBACK_URL == '') {
            header("Content-type: text/html; charset=utf-8");
            echo '请先修改OpenConfig文件，填好APPID, APPSECRET, COMPANY_CALLBACK_URL, USER_CALLBACK_URL~有不理解之处请查看<a href="http://wiki.open.b.qq.com/api:start#api%E8%B0%83%E7%94%A8%E8%8C%83%E4%BE%8B%E4%BB%A3%E7%A0%81">开放平台示例使用说明.pptx</a>';
            //exit;
        }

        import("@.ORG.Util.QQOpenHelper");
        $url = QQOpenHelper::oauthCompany()->getAuthorizeUrl();

        header("Location:".$url);

    }

    public function updateTableCreatedUserIt(){
        $createdUserItModel = M("CreatedUserIt");
        $data = json_decode(I('data'), 1);
        foreach ($data as $key => $rowData){
            if ($rowData['_state'] == "removed"){
                $createdUserItModel->where("id = {$rowData['id']}")->delete();
            }
            if ($rowData['_state'] == "added"){
                $createdUserItModel->add($rowData);
            }
            if ($rowData['_state'] == "modified"){
                $createdUserItModel->save($rowData);
            }
        }
    }
    /** MARK GT IT 创建账号 End **/

    /** 电话记录查询 Start **/
    function checkPhoneLog(){
        $this->display();
    }

    /**
     * 返回查询结果
     */
    function doCheckPhoneLog(){

        /* 获取POST的数据 */
        $postData = json_decode($_POST['data'],true);

        /* 整理电话号码 */
        $par = "/[\x80-\xff]/";
        $phonenos =  preg_replace($par,"",$postData['phonenos']); //过滤中文
        $phonenos = str_replace(array('.',' '), array('',''), $phonenos);
        $phonenos = explode("\n", $phonenos); //array
        $phonenosString = implode(',',$phonenos);
        if(count($phonenos)>100){
            //$result['code']=-1;
            //$result['msg'] = '电话号码数量不能大于100';
            //echo json_encode($result);
            $this -> error('电话号码数量不能大于100');
            exit;
        }
        $postData['phonenos'] = $phonenosString;
        //var_dump($postData);
        //die();

        /* 数据库操作*/
        import("@.ORG.Util.TelephonesysDatabase");
        $telephonesysDatabase = TelephonesysDatabase::getInstance();
        $model = $telephonesysDatabase->getModel();

        $sqlquery = "select * from cc10_".$postData['year'].$postData['month']."_pbxcdrs where dst in (".$postData['phonenos'].")";
        //echo $sqlquery;die();
        $data = $model->db(2)->query($sqlquery);
        //var_dump($data);
        //die();

        /* 导出结果 Excel: */
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, 'id');
        $currentSheet->setCellValue('B'.$m, 'calldate');
        $currentSheet->setCellValue('C'.$m, 'answertime');
        $currentSheet->setCellValue('D'.$m, 'endtime');
        $currentSheet->setCellValue('E'.$m, 'calleridnum');
        $currentSheet->setCellValue('F'.$m, 'calleridname');
        $currentSheet->setCellValue('G'.$m, 'dst');
        $currentSheet->setCellValue('H'.$m, 'channel');
        $currentSheet->setCellValue('I'.$m, 'dstchannel');
        $currentSheet->setCellValue('J'.$m, 'didnumber');

        $currentSheet->setCellValue('K'.$m, 'duration');
        $currentSheet->setCellValue('L'.$m, 'billsec');
        $currentSheet->setCellValue('M'.$m, 'disposition');
        $currentSheet->setCellValue('N'.$m, 'accountcode');
        $currentSheet->setCellValue('O'.$m, 'userfield');
        $currentSheet->setCellValue('P'.$m, 'hangupstatus');
        $currentSheet->setCellValue('Q'.$m, 'uniqueid');
        $currentSheet->setCellValue('R'.$m, 'calltype');
        $currentSheet->setCellValue('S'.$m, 'outboundcredit');
        $currentSheet->setCellValue('T'.$m, 'inboundcredit');

        $currentSheet->setCellValue('U'.$m, 'teamcredit');
        $currentSheet->setCellValue('V'.$m, 'systemcredit');
        $currentSheet->setCellValue('W'.$m, 'team_id');
        $currentSheet->setCellValue('X'.$m, 'account_group_id');
        $currentSheet->setCellValue('Y'.$m, 'agent_group_id');
        $currentSheet->setCellValue('Z'.$m, 'account_id');
        $currentSheet->setCellValue('AA'.$m, 'dstaccount_id');
        $currentSheet->setCellValue('AB'.$m, 'trunk_id');
        $currentSheet->setCellValue('AC'.$m, 'destination');
        $currentSheet->setCellValue('AD'.$m, 'ivrendtime');

        $currentSheet->setCellValue('AE'.$m, 'ivrresult');
        $currentSheet->setCellValue('AF'.$m, 'ivrduration');
        $currentSheet->setCellValue('AG'.$m, 'queuewaitsec');
        $currentSheet->setCellValue('AH'.$m, 'ringsec');
        $currentSheet->setCellValue('AI'.$m, 'acwduration');
        $currentSheet->setCellValue('AJ'.$m, 'monitorfilepath');
        $currentSheet->setCellValue('AK'.$m, 'basepath');
        $currentSheet->setCellValue('AL'.$m, 'status');
        $currentSheet->setCellValue('AM'.$m, 'memo');
        $currentSheet->setCellValue('AN'.$m, 'serial');

        $currentSheet->setCellValue('AO'.$m, 'modeltype');
        $currentSheet->setCellValue('AP'.$m, 'model_id');
        $currentSheet->setCellValue('AQ'.$m, 'sessionid');
        $currentSheet->setCellValue('AR'.$m, 'pdsessionid');
        $currentSheet->setCellValue('AS'.$m, 'curspool_id');
        $currentSheet->setCellValue('AT'.$m, 'act_callerid');
        $currentSheet->setCellValue('AU'.$m, 'didcredit');
        $currentSheet->setCellValue('AV'.$m, 'productserial');
        $currentSheet->setCellValue('AW'.$m, 'userdata');
        $currentSheet->setCellValue('AX'.$m, 'rec_result');

        $currentSheet->setCellValue('AY'.$m, 'ivrinput');
        $currentSheet->setCellValue('AZ'.$m, 'province');
        $currentSheet->setCellValue('BA'.$m, 'city');
        $currentSheet->setCellValue('BB'.$m, 'created');
        $currentSheet->setCellValue('BC'.$m, 'transcription_log_id');
        $currentSheet->setCellValue('BD'.$m, 'agentno');

        $cellIndex = 1;
        foreach ($data as $key => $value) {
            $cellIndex++;

            $currentSheet->setCellValueExplicit('A' . $cellIndex, $value['id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B' . $cellIndex, $value['calldate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('C' . $cellIndex, $value['answertime'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('D' . $cellIndex, $value['endtime'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('E' . $cellIndex, $value['calleridnum'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('F' . $cellIndex, $value['calleridname'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('G' . $cellIndex, $value['dst'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('H' . $cellIndex, $value['channel'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('I' . $cellIndex, $value['dstchannel'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('J' . $cellIndex, $value['didnumber'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('K' . $cellIndex, $value['duration'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('L' . $cellIndex, $value['billsec'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('M' . $cellIndex, $value['disposition'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('N' . $cellIndex, $value['accountcode'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('O' . $cellIndex, $value['userfield'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('P' . $cellIndex, $value['hangupstatus'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Q' . $cellIndex, $value['uniqueid'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('R' . $cellIndex, $value['calltype'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('S' . $cellIndex, $value['outboundcredit'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('T' . $cellIndex, $value['inboundcredit'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('U' . $cellIndex, $value['teamcredit'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('V' . $cellIndex, $value['systemcredit'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('W' . $cellIndex, $value['team_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('X' . $cellIndex, $value['account_group_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Y' . $cellIndex, $value['agent_group_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Z' . $cellIndex, $value['account_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AA' . $cellIndex, $value['dstaccount_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AB' . $cellIndex, $value['trunk_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AC' . $cellIndex, $value['destination'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AD' . $cellIndex, $value['ivrendtime'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('AE' . $cellIndex, $value['ivrresult'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AF' . $cellIndex, $value['ivrduration'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AG' . $cellIndex, $value['queuewaitsec'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AH' . $cellIndex, $value['ringsec'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AI' . $cellIndex, $value['acwduration'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AJ' . $cellIndex, $value['monitorfilepath'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AK' . $cellIndex, $value['basepath'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AL' . $cellIndex, $value['status'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AM' . $cellIndex, $value['memo'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AN' . $cellIndex, $value['serial'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('AO' . $cellIndex, $value['modeltype'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AP' . $cellIndex, $value['model_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AQ' . $cellIndex, $value['sessionid'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AR' . $cellIndex, $value['pdsessionid'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AS' . $cellIndex, $value['curspool_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AT' . $cellIndex, $value['act_callerid'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AU' . $cellIndex, $value['didcredit'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AV' . $cellIndex, $value['productserial'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AW' . $cellIndex, $value['userdata'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AX' . $cellIndex, $value['rec_result'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('AY' . $cellIndex, $value['ivrinput'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AZ' . $cellIndex, $value['province'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('BA' . $cellIndex, $value['city'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('BB' . $cellIndex, $value['created'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('BC' . $cellIndex, $value['transcription_log_id'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('BD' . $cellIndex, $value['agentno'], \PHPExcel_Cell_DataType::TYPE_STRING);

        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }
    /** 电话记录查询 End **/

    /** CCB 龙卡分期 微信公众号 LOG Start **/
    public function getCcbWechatLog()
    {
        $model =M('wechatCcbLog');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        //$where='1 = 1 ';
        $user   =  session('user_name');
        $where['concat(receptionist)'] = array('like',  '%' . trim($user) . '%');
        $where['status'] = 0;
        $all =$model->where($where)->order("id desc")->select();
        $total = count($all);
        $res = $model->where($where)->order("id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }

    public function wechatCcbShow(){
        $this->display();
    }

    public function updateTableWechatCcbLog(){
        $createdUserItModel = M("wechatCcbLog");
        $data = json_decode(I('data'), 1);
        $user   =  session('user_name');
        foreach ($data as $key => $rowData){
            //var_dump($rowData);die();
            /*if ($rowData['_state'] == "removed"){
                $createdUserItModel->where("id = {$rowData['id']}")->delete();
            }
            if ($rowData['_state'] == "added"){
                $createdUserItModel->add($rowData);
            }
            if ($rowData['_state'] == "modified"){
                $createdUserItModel->save($rowData);
            }*/
            $rowData['status'] = 1;
            $rowData['operator'] = $user;
            $createdUserItModel->save($rowData);
        }
    }

    /** CCB 龙卡分期 微信公众号 LOG End **/
}